package com.lch.base.http.callback;

import com.lch.base.http.utils.ParameterizedTypeImpl;
import com.lch.base.http.exception.ApiException;
import com.lch.base.http.exception.HttpCode;
import com.lch.base.http.model.result.BaseResult;

import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.HttpException;
import retrofit2.Response;

/**
 * BaseResult类型的callback，解析数据，可以自定义处理结果
 *
 * @author lee(29487113@qq.com) on 18/2/4
 */
public class RxResultCallBack<T> extends RxBaseCallBack<T> {

    public RxResultCallBack() {
        super();
    }

    public RxResultCallBack(Object tag) {
        super(tag);
    }

    @Override
    public Type getTransType() {
        Type type = super.getTransType(); //获取原来泛型的type
        Type baseResultType = new ParameterizedTypeImpl(BaseResult.class, new Type[]{type}); //重新拼接BaseResult<T>的type
        return baseResultType;
    }

    /**
     * 解析数据，可以自定义处理结果
     * @param response
     * @return
     * @throws Exception
     */
    public T onHandleResponse(Response<ResponseBody> response) throws Exception {
        if (isHttpReponseOk(response)) {
            BaseResult<T> result = transform(response, getTransType()); //调用统一的解析方法，外部可以设置
            if (result != null) {
                //判断跟服务器定义的code是否一样
                if (result.isSuccess()) {
                    T data = result.data;
                    if (data != null) {
                        return data;
                    } else {
                        throw new ApiException(HttpCode.ServerError.RETURE_DATA_NULL);  //返回自定义ApiException
                    }
                } else {
                    //接口返回不成功就抛出服务器带的code和msg
                    throw new ApiException(result.code, result.msg); //返回自定义ApiException-服务器提示
                }
            } else {
                //解析异常，返回result为null
                throw new ApiException(HttpCode.ServerError.ERROR_TRANSFORM);  //返回自定义ApiException
            }
        } else {
            //http级别的异常
            throw new HttpException(response);
        }
    }
}
